package com.flash.javamate.utils;

import com.flash.javamate.entity.ApiDocDataModel;
import com.flash.javamate.handler.DataModelHandler;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author sunyiming
 * @date 2018/8/13
 */
public class HtmlOutput {

    public static void generateApiDoc(File javaFile, File out, DataModelHandler handler) {
        BufferedWriter writer = null;
        try {
        CompilationUnit compilationUnit = JavaParser.parse(javaFile);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out)));
            ApiDocDataModel apiDocDataModel = handler.handle(compilationUnit);
            processGenerate(apiDocDataModel, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void processGenerate(ApiDocDataModel dataModel, File out) throws Exception{
        //1.0 创建配置对象
        //创建Configuration实例，指定FreeMarker的版本
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        //指定模板所在的目录
        ClassLoader classLoader = HtmlOutput.class.getClassLoader();
        URL resource = classLoader.getResource("templates");
        File templatesDir = new File(resource.getPath());
        cfg.setDirectoryForTemplateLoading(templatesDir);
        //设置默认字符集
        cfg.setDefaultEncoding(StandardCharsets.UTF_8.name());
        //设置出现异常处理的方式，开发阶段可以设置为HTML_DEBUG_HANDLER
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);

        //3.0 获取模板
        Template template = cfg.getTemplate("apidoc.ftl");

        //4.0 给模板绑定数据模型
        Writer writer = new OutputStreamWriter(new FileOutputStream(out));
        template.process(dataModel, writer);
    }


}
